package com.edu.servlet;

import com.edu.pojo.Category;
import com.edu.pojo.goods;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class GoodsServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 接收参数
        List<goods> goodsList = new ArrayList<>();
        // 2. jdbc连接数据库

        try {
            // 1. 注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.连接数据库
            String url = "jdbc:mysql://localhost:3306/mall";
            String user = "root";
            String pass = "123456";
            Connection connection = DriverManager.getConnection(url, user, pass);
            if (connection != null) {
                System.out.println("连接到数据库了");
            } else {
                System.out.println("连接数据库失败");
            }

            // 3. 获取发送SQL的对象
            Statement statement = connection.createStatement();
            // 4. 执行sql语句并接收返回的结果
            String sql = "select * from category";
            ResultSet resultSet = statement.executeQuery(sql);

            //5.
            while (resultSet.next()) {
                goods goods = new goods();
                goods.setId(resultSet.getInt("id"));
                goods.setUrl(resultSet.getString("url"));
                goods.setTitle(resultSet.getString("title"));
                goods.setPrice(resultSet.getInt("price"));
                goodsList.add(goods);
            }
            // 6. 设置响应格式（JSON）并处理乱码
            resp.setContentType("application/json;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            //7.
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(resp.getWriter(),goodsList);
            // 8. 释放资源
            statement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
